const { PsychologyKnowledge } = require("../db"); // 只保留这一个导入
const xlsx = require('xlsx');
const { Op, Sequelize } = require('sequelize');

// 添加心理知识文章
exports.addPsychologyKnowledge = async (req, res) => {
    const { title, content, picture } = req.body;
    try {
        const knowledge = await PsychologyKnowledge.create({
            title,
            content,
            picture,
            likes: 0
        });
        res.status(201).json({
            status: 201,
            message: '心理知识添加成功',
            data: knowledge
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '添加心理知识失败',
            error: error.message
        });
    }
};

// 获取心理知识列表
exports.getPsychologyKnowledgeList = async (req, res) => {
    try {
        const knowledgeList = await PsychologyKnowledge.findAll({
            order: [['id', 'DESC']]
        });
        res.status(200).json({
            status: 200,
            message: '获取心理知识列表成功',
            data: knowledgeList
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '获取心理知识列表失败'
        });
    }
};

// 获取指定ID的心理知识文章
exports.getPsychologyKnowledgeById = async (req, res) => {
    try {
        const { id } = req.body;
        
        if (!id || isNaN(id)) {
            return res.status(400).json({
                status: 400,
                message: '无效的文章ID'
            });
        }

        const knowledge = await PsychologyKnowledge.findByPk(id, {
            attributes: ['id', 'title', 'content', 'picture', 'likes']
        });

        if (!knowledge) {
            return res.status(404).json({
                status: 404,
                message: '未找到指定的心理知识文章'
            });
        }

        res.status(200).json({
            status: 200,
            message: '获取心理知识文章成功',
            data: knowledge
        });

    } catch (error) {
        console.error('获取心理知识文章失败:', error);
        res.status(500).json({
            status: 500,
            message: '获取心理知识文章失败',
            error: error.message
        });
    }
};

// 更新心理知识文章
exports.updatePsychologyKnowledge = async (req, res) => {
    const { id } = req.body;
    const { title, content, picture } = req.body;
    try {
        const [updated] = await PsychologyKnowledge.update({
            title,
            content,
            picture
        }, {
            where: { id }
        });
        if (updated) {
            res.status(200).json({
                status: 200,
                message: '心理知识更新成功'
            });
        } else {
            res.status(404).json({
                status: 404,
                message: '未找到指定的心理知识'
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '更新心理知识失败',
            error: error.message
        });
    }
};

// 删除心理知识文章
exports.deletePsychologyKnowledge = async (req, res) => {
    const { id } = req.body;
    try {
        const deleted = await PsychologyKnowledge.destroy({
            where: { id }
        });
        if (deleted) {
            res.status(200).json({
                status: 200,
                message: '心理知识删除成功'
            });
        } else {
            res.status(404).json({
                status: 404,
                message: '未找到指定的心理知识'
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '删除心理知识失败'
        });
    }
};

// 点赞心理知识文章
exports.likePsychologyKnowledge = async (req, res) => {
    const { id } = req.body;
    try {
        const knowledge = await PsychologyKnowledge.findByPk(id);
        if (knowledge) {
            knowledge.likes += 1;
            await knowledge.save();
            res.status(200).json({
                status: 200,
                message: '点赞成功',
                likes: knowledge.likes
            });
        } else {
            res.status(404).json({
                status: 404,
                message: '未找到指定的心理知识'
            });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({
            status: 500,
            message: '点赞失败'
        });
    }
};

// 批量导入心理知识文章
exports.uploadXlsxPsychologyKnowledge = async (req, res) => {
    try {
        console.log(req.file); // 打印文件信息
        const workbook = xlsx.readFile(req.file.path);
        const sheetName = workbook.SheetNames[0];
        const data = xlsx.utils.sheet_to_json(workbook.Sheets[sheetName]);
        
        const importedArticles = [];
        const skippedArticles = [];
        
        for (const article of data) {
            try {
                // 校验必填字段
                if (!article.title || !article.content) {
                    skippedArticles.push({
                        title: article.title || '无标题',
                        reason: '缺少必填字段(title或content)'
                    });
                    continue;
                }
                
                // 检查标题是否已存在
                const articleExist = await PsychologyKnowledge.findOne({
                    where: {
                        title: article.title
                    }
                });
                
                if (articleExist) {
                    skippedArticles.push({
                        title: article.title,
                        reason: '标题已存在'
                    });
                    continue;
                }
                
                // 创建心理知识文章
                const knowledge = await PsychologyKnowledge.create({
                    title: article.title,
                    content: article.content,
                    picture: article.picture || null,
                    likes: article.likes || 0
                });
                
                importedArticles.push(knowledge);
            } catch (error) {
                console.error(`导入文章失败: ${article.title}`, error);
                skippedArticles.push({
                    title: article.title || '无标题',
                    reason: error.message
                });
            }
        }
        
        res.status(200).json({
            status: 200,
            message: '心理知识文章导入完成',
            data: {
                imported_count: importedArticles.length,
                skipped_count: skippedArticles.length,
                imported_articles: importedArticles.map(a => ({
                    id: a.id,
                    title: a.title,
                    picture: a.picture
                })),
                skipped_articles: skippedArticles
            }
        });
    } catch (error) {
        console.error('导入失败:', error);
        res.status(500).json({
            status: 500,
            message: '导入心理知识文章失败',
            error: error.message
        });
    }
};

// 获取随机心理知识
exports.getRandomPsychologyKnowledge = async (req, res) => {
    try {
        const randomKnowledge = await PsychologyKnowledge.findOne({
            order: Sequelize.literal('RAND()'),
            attributes: ['id', 'title', 'content', 'picture', 'likes']
        });

        if (!randomKnowledge) {
            return res.status(404).json({
                status: 404,
                message: '没有找到心理知识文章'
            });
        }

        res.status(200).json({
            status: 200,
            message: '获取随机心理知识成功',
            data: randomKnowledge
        });
    } catch (error) {
        console.error('获取随机心理知识失败:', error);
        res.status(500).json({
            status: 500,
            message: '获取随机心理知识失败',
            error: error.message
        });
    }
};

// 查找心理知识文章
exports.searchPsychologyKnowledge = async (req, res) => {
    try {
        const { keyword, page = 1, pageSize = 10 } = req.query;
        
        if (!keyword || keyword.trim() === '') {
            return res.status(400).json({
                status: 400,
                message: '请输入搜索关键词'
            });
        }

        const whereCondition = {
            [Op.or]: [
                { title: { [Op.like]: `%${keyword}%` } },
                { content: { [Op.like]: `%${keyword}%` } }
            ]
        };

        const { count, rows } = await PsychologyKnowledge.findAndCountAll({
            where: whereCondition,
            attributes: ['id', 'title', 'content', 'picture', 'likes'],
            order: [['id', 'DESC']],
            offset: (page - 1) * pageSize,
            limit: Number(pageSize)
        });

        res.status(200).json({
            status: 200,
            message: '搜索成功',
            data: {
                total: count,
                totalPages: Math.ceil(count / pageSize),
                currentPage: Number(page),
                pageSize: Number(pageSize),
                results: rows.map(item => ({
                    ...item.get({ plain: true }),
                    contentPreview: item.content.substring(0, 100) + '...'
                }))
            }
        });
    } catch (error) {
        console.error('搜索心理知识失败:', error);
        res.status(500).json({
            status: 500,
            message: '搜索心理知识失败',
            error: error.message
        });
    }
};